<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-button type="primary" @click="addRoles()">添加角色</el-button>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['dbbottom', index == 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, index) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[index == 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, index) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      closable
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="small"
              icon="el-icon-edit"
              type="primary"
              @click="editRoles(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="small"
              icon="el-icon-delete"
              type="danger"
              @click="removeRoles(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="small"
              icon="el-icon-setting"
              type="warning"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加角色对话框 -->
      <el-dialog
        title="添加角色"
        :visible.sync="dialogVisible"
        width="50%"
        @close="closeRoles()"
      >
        <el-form :model="rolesForm" :rules="rules" ref="ruleForm">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="rolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="rolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRolesInfo()">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改角色对话框 -->
      <el-dialog
        title="修改角色"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="closeEditRoles()"
      >
        <el-form :model="rolesInfo" :rules="editRules" ref="editRuleForm">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="rolesInfo.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="rolesInfo.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRolesInfo(rolesInfo.roleId)"
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <!-- 分配角色权限对话框 -->
      <el-dialog
        title="分配权限"
        :visible.sync="setRightDialogVisible"
        width="50%"
        @close="setRightDialogClosed()"
      >
        <!-- 权限的树形控件 -->
        <el-tree
          ref="treeRef"
          :data="rightslist"
          :props="treeProps"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="defKeys"
        ></el-tree>
        <span slot="footer">
          <el-button @click="setRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights()">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      dialogVisible: false,
      editDialogVisible: false,
      setRightDialogVisible: false,
      roleId: "",
      defKeys: [],
      // 权限列表
      rightslist: [],
      //  添加角色收集的数据
      rolesForm: {
        roleName: "",
        roleDesc: "",
      },
      rolesInfo: {},
      treeProps: {
        label: "authName",
        children: "children",
      },
      //   添加角色校验
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { max: 40, message: "长度在40个字符", trigger: "blur" },
        ],
      },
      //   修改角色校验
      editRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { max: 40, message: "长度在40个字符", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.getRolesList();
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      } else {
        this.rolesList = res.data;
      }
    },
    // 添加角色按钮
    addRoles() {
      this.dialogVisible = true;
    },
    // 关闭添加角色的对话框
    closeRoles() {
      this.$refs.ruleForm.resetFields();
    },
    // 确认添加角色的按钮
    async addRolesInfo() {
      const { data: res } = await this.$http.post("roles", this.rolesForm);
      if (res.meta.status !== 201) {
        this.$message.error("添加角色失败");
      } else {
        this.$message.success("添加角色成功!");
        this.dialogVisible = false;
        this.getRolesList();
      }
    },
    // 删除角色按钮
    removeRoles(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${id}`);
          if (res.meta.status == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getRolesList();
          } else {
            this.$message.error("删除角色失败");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 编辑角色信息按钮
    async editRoles(id) {
      this.editDialogVisible = true;
      const { data: res } = await this.$http.get(`roles/${id}`);
      if (res.meta.status !== 200) {
        this.$message.error("角色信息查询失败");
      } else {
        this.rolesInfo = res.data;
      }
    },
    // 修改角色信息对话框的关闭事件
    closeEditRoles() {
      this.$refs.editRuleForm.resetFields();
    },
    // 确认修改角色信息
    async editRolesInfo(id) {
      const { data: res } = await this.$http.put(`roles/${id}`, this.rolesInfo);
      if (res.meta.status !== 200) {
        this.$message.error("修改角色信息失败");
      } else {
        this.$message.success("修改角色信息成功!");
        this.editDialogVisible = false;
        this.getRolesList();
      }
    },
    // 删除角色对应权限
    removeRightById(role, rightId) {
      this.$confirm("此操作将永久删除该角色权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          );
          if (res.meta.status == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            // this.getRolesList();
            role.children = res.data;
          } else {
            this.$message.error("删除角色权限失败");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 分配角色权限
    async showSetRightDialog(role) {
      this.roleId = role.id;
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        this.$message.error("获取权限列表失败");
      }
      this.rightslist = res.data;
      this.getLeafKeys(role, this.defKeys);
      this.setRightDialogVisible = true;
    },
    // 通过递归获取角色权限三级id，保存在defKeys数组中
    getLeafKeys(node, arr) {
      // 如果节点中不包含children属性，说明是三级节点，将对应id值添加到数组中去
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClosed() {
      // 每次关闭对话框重新赋为空
      this.defKeys = [];
    },
    // 确认分配角色权限按钮
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: idStr,
        }
      );
      if (res.meta.status !== 200) {
        this.$message.error("分配角色权限失败");
      }
      this.$message.success('分配角色权限成功！')
      this.getRolesList()
      this.setRightDialogVisible = false;
    },
  },
};
</script>

<style>
</style>